Data Storage in Android: SharedPreferences
Table of Contents
We have several data storage solutions for Android app development.
SharedPreferences
SharedPreferences is a light-weight storage for Android to read and store key-value pairs, which is suitable for simple data like app configs, user preferences, login state.
SharedPreferences is, in essence, an .xml file under app-private folder /data/data/<package_name>/shared_prefs.
How to Use?
Retrieval
We mainly have 2 ways to retrieve the SharedPreferences object.
getSharedPreferences(String name, int mode)This method is suitable for scenarios like multiple configurations or the config file should be shared among different components.
Here, the
nameargument tells the file name of the config file. Themodeargument is usuallyContext.MODE_PRIVATE, which means this file can only be accessed by current app.SharedPreferences userPrefs = getSharedPreferences("user_settings", Context.MODE_PRIVATE);getPreferences(int mode)This method is a shortcut for activities to create default, private configuration file, whose name is default to activity’s class name.
This method is only suitable for preference configs within same activity.
SharedPreferences activityPrefs = getPreferences(Context.MODE_PRIVATE);
Writing Data
Writing data is proxied by SharedPreferences.Editor object and follows 3 steps.
- invoke
edit()method to getEditorinstance - invoke
putXXX()method to modify or add data, e.g.,putString(), putInt(), putBoolean() - invoke
apply()orcommit()to submit modification.
// 1. get SharedPreferences.Editor
SharedPreferences.Editor editor = getSharedPreferences("app_config", Context.MODE_PRIVATE).edit();
// 2. put data
editor.putString("username", "AndroidDev");
editor.putInt("login_count", 5);
// 3. submit change
editor.apply();
The key difference between apply() and commit() is about async or sync, which drastically affect speed.
| Feature | apply() |
commit() |
|---|---|---|
| Execution | Async | Sync |
| Return value | / | boolean to indicate success |
| Blocking | Non-Blocking | Blocking |
| Performance | Higher | Lower |
| Data consistency | No guarantee | Immediate ensure |
In most cases, we should use apply()
Reading Data
We just simply invoke getXXX() of SharedPreferences objects.
EncryptedSharedPreferences
Standard SharedPreferences stores data in bear xml files. If we want to store passwords, tokens, we should use EncryptedSharedPreferences, which automatically encrypts keys and values.
First, we have to add dependency in build.gradle of AndroidX Security library.
dependencies {
implementation "androidx.security:security-crypto:1.1.0-alpha06"
}